<?php
namespace Operations\Controller;
use Common\Controller\AdminbaseController;
use Library\Wx;
use Think\Log;

class ActivityController extends AdminbaseController {
	protected $event_model,$cards_model,$prizes_order_model,$groups_model,$event_area_model,$region_model;

	function _initialize() {
		parent::_initialize();
		$this->event_model= D("Events");
		$this->cards_model= D("Card");
		$this->prizes_order_model = D("PrizesOrder");
		$this->groups_model = D("Groups");
		$this->event_area_model = D("EventArea");
		$this->store_model = D("Store");
		$this->region_model = D("Region");
		$this->device_model = D("Device");
		$this->groupsdevice_model = D("GroupsDevice");
        $this->event_prize_pool_model = D('event_prize_pool');
	}
	function index(){
		$this->_lists();
		$this->display();
	}

	function add(){
		$this->_view_cards_list();
		$province = $this->region_model->where(array('level'=>1))->select();
		$city = $this->region_model->where(array('level'=>2))->select();
		$region_model = $this->region_model->where(array('parent_id'=>100000))->order('LENGTH(name) asc,id asc')->select();
		$customGroupsModel = $this->groups_model->where(array('status'=>1))->select();
		$groupsModel = C('SHOP_TYPE');

		$this->_view_add_event_type();
        $wxssap = Wx::searchShakeAroundPage('',0,50);
		$this->assign("wxssap", $wxssap['data']['pages']);
		$this->assign("province", $province);
		$this->assign("city", $city);
		$this->assign("areas", $region_model);
		$this->assign("customGroups", $customGroupsModel);
		$this->assign("groups", $groupsModel);
		$this->display();
	}
	function add_activity(){
		if (IS_POST) {
			if(!get_current_admin_id()){
				$this->error("您不属于任何组，请先创建组");
			}
			if(!I("post.event_name") || !I("post.event_intro")){
				$this->error("请填写活动名称、活动介绍等内容");
			}
			if(!I('post.wx_page_id')){
				if(!I('post.wx_page_id2')){
					$_POST['wx_page_id'] = C('DEFAULT_WX_ACTIVITYID');
				}else{
					$_POST['wx_page_id'] = I('post.wx_page_id2');
				}
			}
			$bind_cards = implode(',', I("post.bind_cards"));
			$bind_cards_percentage = implode(',',I("post.bind_cards_percentage"));

            $bind_cards = I("post.bind_cards");
            $bind_cards_percentage = I("post.bind_cards_percentage");
			if(!$bind_cards){
				$bind_cards = '';
				$bind_cards_percentage = '';
			}
            $_POST['bind_cards'] = implode(',', $bind_cards);
            $_POST['bind_cards_percentage'] = implode(',', $bind_cards_percentage);
			if(!is_numeric(I('post.event_weight_factor'))){
				$this->error("您输入的内容不是数字，请核对");
			}
			$_POST['created_at'] = date("Y-m-d H:i:s");
            $_POST['updated_at'] = date("Y-m-d H:i:s");
			$_POST['created_by'] = get_current_admin_id();
			$_POST['event_status'] = 1;
			$_POST['userid'] = get_current_admin_id();
			$_POST['ugid'] = get_current_adminug_id();
			if($_FILES){
				$Aliyun = new \Aliyun\Controller\AliyunController();
				if($_FILES["bg_pic"]){
					$bg_pic = $Aliyun->save($_FILES["bg_pic"],'img/'.CONTROLLER_NAME);
					if(!$bg_pic['error']){
					$_POST['bg_pic'] =$bg_pic['path'].$bg_pic['name'];
					}else{
						$this->error('图像上传失败');
					}
				}
				if($_FILES["center_pic"]){
				$center_pic = $Aliyun->save($_FILES["center_pic"],'img/'.CONTROLLER_NAME);
					if(!$center_pic['error']){
						$_POST['center_pic'] =$center_pic['path'].$center_pic['name'];
					}else{
						$this->error('图像上传失败');
					}
				}
				if($_FILES["loding_pic"]){
				$loding_pic = $Aliyun->save($_FILES["loding_pic"],'img/'.CONTROLLER_NAME);
					if(!$loding_pic['error']){
						$_POST['loding_pic'] =$loding_pic['path'].$loding_pic['name'];
					}else{
						$this->error('图像上传失败');
					}
				}
			}
			$eventid = $this->event_model->add($_POST);
			if ($eventid) {
				$pareas = I('post.areas');
				$pareas = explode(',',$pareas[0]);
				if($pareas){
					$areaData = array();
					foreach($pareas as $area){
						$data = array();
						$data['event_id'] = $eventid;
						$data['type'] = 0;
						$data['area_id'] = $area;
						$areaData[] = $data;
					}
					if(I('post.group')){
						foreach(I('post.groups') as $k=>$id){
							$groups['event_id'] = $eventid;
							$groups['type'] = 2;
							$groups['area_id'] =$id;
							$areaData[] = $groups;
						}
						foreach(I('post.customGroups') as $k=>$id){
							$customGroups['event_id'] = $eventid;
							$customGroups['type'] = 1;
							$customGroups['area_id'] =$id;
							$areaData[] = $customGroups;
						}
						if (!I('post.groups') && !I('post.customGroups')) {
							$groups['event_id'] = $eventid;
							$groups['type'] = 2;
							$groups['area_id'] =0;   //0 代表没有限定活动的标签
							$areaData[] = $groups;
						}
					} else {
						$groups['event_id'] = $eventid;
						$groups['type'] = 2;
						$groups['area_id'] =0;   //0 代表没有限定活动的标签
						$areaData[] = $groups;
					}
					$this->event_area_model->addAll($areaData);

                    foreach ($bind_cards as $k => $id) {
                        $prize['event_id'] =  $eventid;
                        $prize['card_id'] = $id;
                        $prize['weight'] = $bind_cards_percentage[$k];
                        $prizeList[] = $prize;
                    }
                    $this->event_prize_pool_model->addAll($prizeList);
				}
				$this->success("添加成功！",U('Activity/index'));
			} else {
				$this->error("添加失败！");
			}
		}
	}

	public function edit(){
		$id =  intval(I("get.id"));
		$event = $this->event_model->where("id=$id")->find();
		$this->_view_cards_list();
		$areas_model = $this->event_area_model->where(array('event_id'=>$id,'type'=>0))->order('id desc')->select();
		if($areas_model){
			foreach($areas_model as$k=>$area){
				$areas[$k] =$area['area_id'];
			}
			$areanames_model = $this->region_model->where(array('code'=>array('in',$areas)))->select();
			foreach($areanames_model as$k=>$area){
				$areanames[$k] =$area['shortname'];
			}
		}
		$this->_view_add_event_type();
        $wxssap = Wx::searchShakeAroundPage('',0,50);
		$this->assign("wxssap", $wxssap['data']['pages']);
		$event_groups = $this->event_area_model->where(array('event_id'=>$id,'type'=>2))->select();
		$event_customGroups = $this->event_area_model->where(array('event_id'=>$id,'type'=>1))->select();
		$province = $this->region_model->where(array('level'=>1))->select();
		$city = $this->region_model->where(array('level'=>2))->select();
		$customGroupsModel = $this->groups_model->where(array('status'=>1))->select();
		$groupsModel = C('SHOP_TYPE');

        $cardList = $this->event_prize_pool_model->field('card_id, weight')->where(array('event_id'=>$id))->select();

        if (!$cardList) {
            $bind_cards = explode(',', $event['bind_cards']);
            $bind_cards_percentage = explode(',', $event['bind_cards_percentage']);
            foreach ($bind_cards as $k => $card_id) {
                $card['card_id'] = $card_id;
                $card['weight'] = $bind_cards_percentage[$k];
                $cardList[] = $card;
                unset($card);
            }
        }
        $event['bind_cards'] = $cardList;
		$this->assign("event_areas", $areas);
		$this->assign("event_groups", $event_groups);
		$this->assign("event_customGroups", $event_customGroups);
		$this->assign("event_names", $areanames);
		$this->assign("province", $province);
		$this->assign("city", $city);
		$this->assign("customGroups", $customGroupsModel);
		$this->assign("groups", $groupsModel);
		$this->assign("event", $event);
		$this->assign("urlimg", C('IMG_PATH'));
		$this->display();
	}
	public function edit_activity(){
		if (IS_POST) {
			if(!I("post.event_name") || !I("post.event_intro")){
				$this->error("请填写活动名称、活动介绍等内容");
			}
			if(!is_numeric(I('post.event_weight_factor'))){
				$this->error("您输入的内容不是数字，请核对");
			}
			if(!implode(',',I("post.bind_cards"))){
				$this->error("请选择物料");
			}
			if(!I('post.wx_page_id')){
				if(!I('post.wx_page_id2')){
					$_POST['wx_page_id'] = C('DEFAULT_WX_ACTIVITYID');
				}else{
					$_POST['wx_page_id'] = I('post.wx_page_id2');
				}
			}
            $_POST['updated_at'] = date("Y-m-d H:i:s");
            $bind_cards = I("post.bind_cards");
            $bind_cards_percentage = I("post.bind_cards_percentage");
			$_POST['bind_cards'] = implode(',', $bind_cards);
			$_POST['bind_cards_percentage'] = implode(',', $bind_cards_percentage);
			$_POST['userid'] = get_current_admin_id();
			if($_FILES){
				$Aliyun = new \Aliyun\Controller\AliyunController();
                if (!empty($_FILES["newbg_pic"]) && !empty($_POST["bg_pic"])) {
					$Aliyun->delete($_POST['bg_pic']);
				}
                if (!empty($_FILES["newcenter_pic"]) && !empty($_POST["newcenter_pic"])) {
					$Aliyun->delete($_POST['center_pic']);
				}
				if($_FILES["newbg_pic"]){
					$bg_pic = $Aliyun->save($_FILES["newbg_pic"],'img/'.CONTROLLER_NAME);
					if(!$bg_pic['error']){
					$_POST['bg_pic'] =$bg_pic['path'].$bg_pic['name'];
					}else{
						$this->error('图像上传失败');
					}
				}
				if($_FILES["newcenter_pic"]){
				$center_pic = $Aliyun->save($_FILES["newcenter_pic"],'img/'.CONTROLLER_NAME);
					if(!$center_pic['error']){
						$_POST['center_pic'] =$center_pic['path'].$center_pic['name'];
					}else{
						$this->error('图像上传失败');
					}
				}
				if($_FILES["newloding_pic"]){
				$loding_pic = $Aliyun->save($_FILES["newloding_pic"],'img/'.CONTROLLER_NAME);
					if(!$loding_pic['error']){
						$_POST['loding_pic'] =$loding_pic['path'].$loding_pic['name'];
					}else{
						$this->error('图像上传失败');
					}
				}
			}
			if ($this->event_model->save($_POST)) {
				$this->event_area_model->where(array('event_id'=>I('post.id')))->delete();
				$pareas = I('post.areas');
				$pareas = explode(',',$pareas[0]);
				if($pareas){
					$areaData = array();
					foreach($pareas as $area){
						$data = array();
						$data['event_id'] = $_POST['id'];
						$data['type'] = 0;
						$data['area_id'] = $area;
						$areaData[] = $data;
					}
					if(I('post.group')){
						foreach(I('post.groups') as $k=>$id){
							$groups['event_id'] = $_POST['id'];
							$groups['type'] = 2;
							$groups['area_id'] = $id;
							$areaData[] = $groups;
						}
						foreach(I('post.customGroups') as $k=>$id){
							$customGroups['event_id'] = $_POST['id'];
							$customGroups['type'] = 1;
							$customGroups['area_id'] =$id;
							$areaData[] = $customGroups;
						}
						if (!I('post.groups') && !I('post.customGroups')) {
							$groups['event_id'] = $_POST['id'];
							$groups['type'] = 2;
							$groups['area_id'] =0;   //0 代表没有限定活动的标签
							$areaData[] = $groups;
						}
					} else {
						$groups['event_id'] = $_POST['id'];
						$groups['type'] = 2;
						$groups['area_id'] =0;   //0 代表没有限定活动的标签
						$areaData[] = $groups;
					}
					$this->event_area_model->addAll($areaData);

                    $this->event_prize_pool_model->where(array('event_id'=>I('post.id')))->delete();
                    foreach ($bind_cards as $k => $id) {
                        $prize['event_id'] =  $_POST['id'];
                        $prize['card_id'] = $id;
                        $prize['weight'] = $bind_cards_percentage[$k];
                        $prizeList[] = $prize;
                    }

                    $this->event_prize_pool_model->addAll($prizeList);
				}
				$this->success("修改活动成功！",U('Activity/index'));
			} else {
				$this->error("修改活动失败！");
			}
		}
	}

    private function event_typelist() {
		$eventTypeList =
		array(
			array(
	            array('id' => '1', 'name'=>'摇一摇'),
	            array('id' => '2', 'name'=>'扫一扫'),
	        ),
	        array(
	            array('id' => '1', 'name'=>'待审核'),
	            array('id' => '2', 'name'=>'活动中'),
	            array('id' => '3', 'name'=>'已结束'),
	        )
		);
		return $eventTypeList;
    }
    private function _view_add_event_type() {
		$eventTypeList = $this->event_typelist();
        $this->assign('eventTypeList', $eventTypeList[0]); //活动类型列表
        $this->assign('eventStatusList', $eventTypeList[1]); //活动类型列表
    }

	private function _view_cards_list() {
		$userid = get_current_admin_id();
		$roleid =  get_current_adminrole_id();
		if (!$userId) {
			if ($roleid >= 20) {
				$search[] = array('userid'=>$userid);
			}
		}

		$datetime = date("Y-m-d H:i:s",time());
		$where = 'yy_card.end_at >= "'.$datetime.'"';

		$search['card_status'] =array(in, '1,2,4');
        $cardsList = $this->cards_model->where($search)->where($where)->select();
        $this->assign('cardsList', $cardsList); //活动归属列表
    }

	private  function _lists(){
		$userid = get_current_admin_id();
		$roleid =  get_current_adminrole_id();
		if (!$userId) {
			if ($roleid >= 20) {
				$search[] = array('userid'=>$userid);
			}
		}

		if(I('param.')){
            if(I('param.event_type')){
                    $search[] = array('event_type'=>I('param.event_type'));
                    $_GET['event_type'] = I('param.event_type');
            }
            if(I('param.start_time')){
                    $search[] = array('date(created_at)'=>array('egt',I('param.start_time')));
                    $_GET['start_time'] = I('param.start_time');
            }
            if(I('param.end_time')){
                    $search[] = array('date(created_at)'=>array('elt',I('param.end_time')));
                    $_GET['end_time'] = I('param.end_time');
            }
            if(I('param.keyword')){
                    $search[] = array('event_name'=>array("like","%".I('param.keyword')."%"));
                    $_GET['keyword'] = I('param.keyword');
            }
		}
		$count=$this->event_model
		->where($search)
		->count();

		$page = $this->page($count, 50);

		$event=$this->event_model
		->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("end_at DESC")->select();
		if($event){
			foreach($event as$euser){
				$uid[] =$euser['created_by'];
			}
			$users=M("users")->field("id,user_login")->where(array('id'=>array('in',$uid)))->select();
		}
		$this->_view_add_event_type();
		$this->assign("users", $users);
		$this->assign("Page", $page->show('Admin'));
		$this->assign("current_page", $page->GetCurrentPage());
		unset($_GET[C('VAR_URL_PARAMS')]);
		$this->assign("count", $count);
		$this->assign("events", $event);
	}

	function delete(){
		if(isset($_GET['id'])){
			$id = intval(I("get.id"));
			$prizes = $this->prizes_order_model->where(array("event_id"=>$id))->count();
			if (!$prizes) {
				$img = $this->event_model->where("id=$id")->find();
				if($img['event_icon']){
					$Aliyun = new \Aliyun\Controller\AliyunController();
					$Aliyun->delete($img['event_icon']);
				}
				$this->event_model->where("id=$id")->delete();
				$this->event_area_model->where("event_id=$id")->delete();
				$this->success("活动删除成功");
			} else {
				$this->error("此活动已有 < $prizes >名用户参与，不可删除。");
			}
		}
	}
    public function del_img(){
    	if (I("get.id")) {
    		$event = $this->event_model->where(array('id'=>I("get.id")))->find();
			$img = $event[I("get.type")];
			$type =I("get.type");
			if($img){
				$Aliyun = new \Aliyun\Controller\AliyunController();
				$Aliyun->delete($img);
			}
    		if ($this->event_model->where(array('id'=>I("get.id")))->setField($type,'')) {
    			$this->success("图片删除成功！");
    		} else {
    			$this->error('图片删除失败！');
    		}
    	} else {
            Log::record('delete img fail, detail reason: '.$this->event_model->getError());
            $this->error('图片删除失败！');
    	}
    }

	public function up(){
    	if (I("get.id")) {
    		$rst = $this->event_model->where(array('id'=>I("get.id")))->setField('event_status','2');
    		if ($rst) {
    			$this->success("活动上线成功！");
    		} else {
    			$this->error('活动上线失败！');
    		}
    	} else {
			$this->error($this->event_model->getError());
    	}
    }

    public function down(){
    	if (I("get.id")) {
    		$rst = $this->event_model->where(array('id'=>I("get.id")))->setField('event_status','3');
    		if ($rst) {
    			$this->success("活动下线成功！");
    		} else {
    			$this->error('活动下线失败！');
    		}
    	} else {
			$this->error($this->event_model->getError());
    	}
    }
}
